package com.demo.search.mapper;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : YU.TAN
 * @date : 2021/9/18 17:34
 *  ElasticSearch高亮配置
 */
@Slf4j
@Component
public class HighlightResultHelper implements SearchResultMapper {
    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
        List<T> results=new ArrayList<>();
        for (SearchHit hit: searchResponse.getHits()) {
            if (hit !=null){
                T result=null;
                if (StringUtils.hasText(hit.getSourceAsString())){
                    result= JSONObject.parseObject(hit.getSourceAsString(),aClass);
                }
//高亮查询
                for (HighlightField field: hit.getHighlightFields().values()) {
//                    PropertyUtils
                }
            }
        }
        return null;
    }

    @Override
    public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
        return null;
    }
}
